<script>
import addressMapSelect from "@/view/components/addressMapSelect.vue";
import {getDist,getDept, getDistTree} from "@/util/util";
import fileUpload from "@/view/components/fileUpload.vue";

export default {
  data() {
    return {
      dialogVisible: false,
      diaWidth: '30%',
      mapVisible: false,
      addressMap: '',
      gmForm: {},
      active: 'add',
      dictTree: null,
      deptTree:null,
      timeout: null,
    }
  },
  components: {
    addressMapSelect: addressMapSelect,
    fileUpload: fileUpload
  },
  props: {
    tableColumns: Array,
    tableConfig: Object
  },
  mounted() {
    this.clearForm();
    if (this.tableConfig.control === 't-transportation-company-information') {
      this.diaWidth = '40%';
    }
    getDist().then(res => {
      this.dictTree = res;
    });
    getDept().then(res => {
      this.deptTree = res;
    });
  },
  methods: {
//data：要遍历的数据， target：查找目标， result用于装查找结果的数组
    findParent(data, target, result) {
      for (let i in data) {
        let item = data[i]
        if (item.districtCode == target.districtCode) {
          //将查找到的目标数据加入结果数组中
          //可根据需求unshift(item.id)或unshift(item)
          result.unshift(item.districtCode)
          return true
        }
        if (item.children && item.children.length > 0) {
          let ok = this.findParent(item.children, target, result)
          console.log('okokokokokokokok',ok)
          if (ok) {
            result.unshift(item.districtCode)
            return true
          }
        }
      }
      //走到这说明没找到目标
      return false
    },
   //code为左侧区划树编码

    openDia(sendMsg, active,treeData,code) {
      this.active = active;
      if (active === 'add') this.clearForm(treeData,code)
      else this.setBackData(sendMsg);
      this.dialogVisible = true;
    },
    clearForm(treeData,code) {
      this.tableColumns.forEach(x => {
        this.$set(this.gmForm, x.id, '')
        if (x.searchType === 'state') this.$set(this.gmForm, x.id, '01')
        if (x.searchType === 'upload') this.$set(this.gmForm, x.id, [])
        if (x.id === 'districtCode'){
          let target = { "districtCode": code, }
          let result = []
          this.findParent(treeData, target, result)
          this.$set(this.gmForm, x.id,result)
        }
      })
      console.log('55555555this.tableColumns',this.tableColumns)
      setTimeout(()=>{
        this.$refs['form']?.clearValidate();
      },100)
    },
    setBackData(sendMsg) {
      this.gmForm = {...sendMsg}
      if(sendMsg.state === '启用'|| sendMsg.state === '有效'){
        this.gmForm.state = '01'
      }
      if(sendMsg.state === '禁用'|| sendMsg.state === '无效'){
        this.gmForm.state = '02'
      }
      // this.gmForm.state = sendMsg.state === '启用' ? '01' : '02';
      // this.gmForm.state = sendMsg.state === '有效' ? '01' : '02';
      this.gmForm.isCreateStation = sendMsg.stationName ? '01' : '02';
      this.$refs['form']?.clearValidate();
    },
    handleClose() {
      this.dialogVisible = false;
      this.$refs['form']?.clearValidate();
    },
    pullData() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          this.submitData();
        } else {
          console.log('校验失败');
          return false;
        }
      });

    },
    submitData() {
      //如果是学生的添加，经纬度和家庭住址需要进行特别的处理
      if (this.tableConfig.control === '/api/tStudent') {
        this.gmForm['homeAddress'] = this.addressMap.formattedAddress;
        this.gmForm['lng'] = this.addressMap.location.lng;
        this.gmForm['lat'] = this.addressMap.location.lat;
      }
      //如果是路线管理，参数做出调整
      if (this.tableConfig.control === 't-route') {
        this.gmForm = {
          stationCodeStart: this.gmForm['stationCodeStartEn'],
          stationCodeEnd: this.gmForm['stationCodeEndEn'],
          passingPoindCode: this.gmForm['passingPoindCodeEns'].join(','),
          routeName: this.gmForm['routeName']
        }
      }
      for (let x in this.gmForm) {
        //站点管理区划问题修改

        if (x === 'districtCode' &&  Array.isArray(this.gmForm[x])) {//如果是区划，则只取数组最后一个区划
          this.gmForm[x] = this.gmForm[x][this.gmForm[x].length - 1]
        }

        if (x === 'organizationIdPath' && Array.isArray(this.gmForm[x])) { //如果是上傳的圖片，數組以逗號分割組合成為字符串傳入後端接口
          this.gmForm[x] = this.gmForm[x]?.join(',')
        }
        this.tableColumns.forEach(c => { //将翻译后的数据翻译回来提交
          if (c.id === x && c.dictObj) {
            for (let l in c.dictObj) {
              if (c.dictObj[l] === this.gmForm[x]) {
                this.gmForm[x] = l;
              }
            }
          }
        })
      }
      //添加的时候去掉所有主键
      // delete this.gmForm[this.tableConfig.mainKey]
      delete this.gmForm['createDate']
      delete this.gmForm['createUserName']
      let url = this.active === 'add'
      if (this.active === 'add') this.$HttpService.post(`${this.tableConfig.control}/add`, this.gmForm).then(() => {
        this.$message.success('添加成功！')
        this.dialogVisible = false;
        this.$emit('onSuccess');
      })
      else {
        this.$HttpService.put(`${this.tableConfig.control}/update`, this.gmForm).then(() => {
          this.$message.success('修改成功！')
          this.dialogVisible = false;
          this.$emit('onSuccess');
        })
      }
    },
    getLocation(x) {
      this.$refs.addressMap.getLocationFromAddress(x)
    },
    setAddress(address) {
      this.mapVisible = false;
      this.addressMap = address;
    },
    querySearchAsync(queryString, cb) {
      let restaurants = [];
      this.$HttpService.get(`/t-vehicle-information/findCarBrand?carBrand=${queryString}`).then((res) => {
        // restaurants = res;
        res.forEach(item => {
          restaurants.push({
            value: item
          })
        })
        cb(restaurants);
      })
    },
    handleSelect(item) {
      console.log(item);
    },
    handleChangeGroup(prop, val) {
      setTimeout(() => {
        this.$refs['form'].validateField(`${prop}`)
        console.log(val)
      }, 1000)
    }
  }
}
</script>

<template>
  <el-dialog
      title="新增或修改"
      :visible.sync="dialogVisible"
      :width="diaWidth"
      :before-close="handleClose">
    <div class="center">
      <div class="row">
        <el-form ref="form" label-width="120px" :model="gmForm">
          <el-form-item
              :rules="!x.notMust?{required:true,message:`请录入${x.label}信息`,trigger:['change','blur','focus']}:{}"
              :label="x.label" v-for="x in tableColumns" :prop="x.id" v-if="!x.addHide">
            <el-input v-if="x.searchType === 'input'" :placeholder="`请输入${x.label}`"
                      v-model.trim="gmForm[x.id]"></el-input>
            <el-autocomplete v-if="x.searchType === 'advise-input'" v-model="gmForm[x.id]"
                             :fetch-suggestions="querySearchAsync"
                             :placeholder="`请输入${x.label}`" @select="handleSelect"></el-autocomplete>

            <el-select v-if="x.searchType === 'select'" v-model="gmForm[x.id]" placeholder="请选择">
              <el-option v-for="item in x.dictList" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
            <el-select v-if="x.searchType === 'more-select'" v-model="gmForm[x.id]" multiple
                       placeholder="请选择">
              <el-option v-for="item in x.dictList" :key="item.value" :label="item.label"
                         :value="item.value"></el-option>
            </el-select>
            <el-date-picker v-if="x.searchType === 'year'" v-model="gmForm[x.id]" type="year" format="yyyy" value-format="yyyy"
                            :picker-options="{disabledDate(time) { return time.getTime() > Date.now() - 8.64e6 }}"
                            placeholder="选择年"></el-date-picker>
            <el-date-picker v-if="x.searchType === 'date'" v-model="gmForm[x.id]" type="date"
                            format="yyyy-MM-dd" value-format="yyyy-MM-dd"
                            :picker-options="{disabledDate(time) { return time.getTime() > Date.now() - 8.64e6 }}"
                            placeholder="选择日期"></el-date-picker>

            <el-cascader :show-all-levels="false" v-if="x.searchType === 'dict'" :options="dictTree" v-model="gmForm[x.id]"
                         @change="handleChangeGroup(x.id,gmForm[x.id])" :props="{
                                      label:'districtName',
                                      value:'districtCode',
                                      }"></el-cascader>
            <el-cascader v-if="x.searchType === 'dept'" :options="deptTree" v-model="gmForm[x.id]"
                         @change="handleChangeGroup(x.id,gmForm[x.id])" :props="{
                                      label:'deptName',
                                      value:'deptId',
                                      checkStrictly: true}" clearable></el-cascader>
            <el-switch v-if="x.searchType === 'state'" v-model="gmForm[x.id]"
                       active-color=" #13ce66" inactive-color="#ff4949" active-value="01"
                       inactive-value="02">
            </el-switch>
            <fileUpload v-if="x.searchType === 'upload'" :model="gmForm[x.id]"></fileUpload>
            <span style="padding-left: 20px" v-if="active=='update' && x.id === 'isCreateStation'">{{ gmForm['stationName'] }}</span>
          </el-form-item>
        </el-form>
      </div>
      <div class="opa">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="pullData">确 定</el-button>
      </div>
    </div>
  </el-dialog>
</template>

<style scoped>
.center {
  background-repeat: no-repeat;
  background-position: right center;
  background-size: 15%;
  min-height: 400px;

  .row {
    padding-left: 30px;
    width: 80%;
    text-align: center;
  }

  .opa {
    padding-left: 130px;
      text-align: right;
  }
}

::v-deep .map-com {
  width: 200px;
  height: 200px;
  background: #00a0e9;
}

::v-deep .el-input {
  width: 100% !important;
}

::v-deep .el-select {
  width: 100% !important;
}

::v-deep .el-cascader {
  width: 100% !important;
}

::v-deep .el-form-item__content {
  text-align: justify !important;
}

::v-deep .el-autocomplete {
  width: 100% !important;
}
</style>
